﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml;
using AlipaySDK.Dto.Auth;
using Common.Logging;
using AlipaySDK.Helper;
using User.Api.Helpers;
using User.Api.Models;

namespace User.Api.Controllers
{
    [AllowAnonymous]
    public class ApiAopController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(ApiAopController));
        /// <summary>
        /// 支付宝后台验证地址（使用Post），支付宝后台的“开发者网关”的Url填写如：http://wxbitcare.bitcare.cn/api/apiaop/Interaction
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionName("Interaction")]
        public HttpResponseMessage Validation()
        {
            string strBody = Request.Content.ReadAsStringAsync().Result;

            Dictionary<string, string> dict = AlipayNotifyHelper.GetAlipayRequstParams(strBody);
            if (strBody.Contains("alipay.service.check"))
            {
                //验证网关
                if ("alipay.service.check".Equals(dict["service"]))
                {
                    var isValid = false;
                    string rtnstr = Auth.Verifygw(dict, out isValid);
                    if (isValid)
                    {
                        return new HttpResponseMessage
                        {
                            StatusCode = HttpStatusCode.OK,
                            Content = new StringContent(rtnstr)
                        };
                    }
                }
            }
            else
            {
                string bizContent = dict["biz_content"];
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(bizContent);
               
                string eventType = xmlDoc.SelectSingleNode("//EventType")?.InnerText ?? "";
                string fromUserId = xmlDoc.SelectSingleNode("//FromUserId")?.InnerText ?? "";
                string actionParam = xmlDoc.SelectSingleNode("//ActionParam")?.InnerText ?? "";
                string agreementId = xmlDoc.SelectSingleNode("//AgreementId")?.InnerText ?? "";
                //string UserInfo = xmlDoc.SelectSingleNode("//UserInfo")?.InnerText ?? "";
                string accountNo = xmlDoc.SelectSingleNode("//AccountNo")?.InnerText ?? "";
                string appId = xmlDoc.SelectSingleNode("//AppId")?.InnerText ?? "";
                string createTime = xmlDoc.SelectSingleNode("//CreateTime")?.InnerText ?? "";
                string msgType = xmlDoc.SelectSingleNode("//MsgType")?.InnerText ?? "";
                string content = xmlDoc.SelectSingleNode("//Content")?.InnerText ?? "";

                if (!"alipay.mobile.public.message.notify".Equals(dict["service"]))
                {
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Error");
                }
                string reponseString = string.Empty;
                AliMessageHandler handler = new AliMessageHandler();
                if ("follow".Equals(eventType))
                {  //关注消息
                   //response.MsgType = "follow";
                   //// ActionParam={"scene":{"sceneId": "1234"}}
                    var codeinfo = Newtonsoft.Json.JsonConvert.DeserializeObject<CreateQrCodeResultRequest.Code_Info>(actionParam);
                    var eventKey = codeinfo == null ? "" : codeinfo.Scene.SceneId;
                    handler.OnEvent_SubscribeRequest(fromUserId, eventKey);
                    var url = MessageHelper.GetH5Url("");
                    reponseString = SendMessage.ReceivemsgResponse(appId, url, fromUserId);
                }
                else if ("unfollow".Equals(eventType))
                {   //取消关注
                    handler.OnEvent_UnsubscribeRequest(fromUserId);
                    //SendMessage.SendText(appId, fromUserId, unFollowHandler);
                }
                else if ("click".Equals(eventType))
                {
                   #region 处理菜单点击
                                            //菜单点击
                    switch (actionParam)
                    {
                        case "hospital_info": //医院信息
                            //发送客服消息
                            SendMessage.SendPhoto(appId, fromUserId, handler.GetHospitalInfo(fromUserId));
                            break;
                        case "department_info": //科室信息
                            //发送客服消息
                            SendMessage.SendPhoto(appId, fromUserId, handler.GetDepartmentInfo(fromUserId));
                            break;
                        case "doctor_info": //医生信息
                            //发送客服消息
                            SendMessage.SendPhoto(appId, fromUserId, handler.GetDoctorInfo(fromUserId));
                            break;
                        case "notice_info": //医院公告
                            //发送客服消息
                            SendMessage.SendPhoto(appId, fromUserId, handler.GetHospNoticeInfo(fromUserId));
                            break;
                        case "service_guahao": //当天挂号&取号
                            SendMessage.SendText(appId, fromUserId, handler.GetWxAppt(fromUserId));
                            break;
                        case "service_quhao": //预约挂号
                            SendMessage.SendText(appId, fromUserId, handler.GetOtherAppt(fromUserId));
                            break;
                        case "service_hezhenduilie": //候诊队列
                            SendMessage.SendText(appId, fromUserId, handler.GetQueue(fromUserId));
                            break;
                        case "service_jiuzhenjiaofei": //就诊缴费
                            SendMessage.SendText(appId, fromUserId, handler.GetBill(fromUserId));
                            break;
                        case "service_qubaogaodan": //取报告单
                            SendMessage.SendText(appId, fromUserId, handler.GetHealthReport(fromUserId));
                            break;
                        case "my_danju": //我的单据
                            SendMessage.SendText(appId, fromUserId, handler.GetReport(fromUserId));
                            break;
                        case "my_juzhenka": //我的就诊卡
                            SendMessage.SendText(appId, fromUserId, handler.GetCard(fromUserId));
                            break;
                        case "serviceDescription": //服务说明
                            SendMessage.SendText(appId, fromUserId, handler.GetServiceDescription(fromUserId));
                            break;
                        case "service_manyidudiaocha": //满意度调查
                            SendMessage.SendText(appId, fromUserId, handler.GetServiceSIPaper(fromUserId));
                            break;
                        case "service_inpatienthistory": //住院历史
                            SendMessage.SendText(appId, fromUserId, handler.GetInpatientHistory(fromUserId));
                            break;
                        case "service_dinner": //订餐服务
                            SendMessage.SendText(appId, fromUserId, handler.GetDinnerInfo(fromUserId));
                            break;
                        default:
                        {
                            SendMessage.SendText(appId, fromUserId, "功能开发中，敬请期待！");
                        }
                            break;
                    }

                    #endregion
                }
                else if ("enter".Equals(eventType))
                {
                    //带参数二维码扫码事件
                    //response.MsgType = "enter";
                    //// ActionParam={"scene":{"sceneId": "1234"}}
                    var codeinfo = Newtonsoft.Json.JsonConvert.DeserializeObject<CreateQrCodeResultRequest.Code_Info>(actionParam);
                    var eventKey = codeinfo == null ? "" : codeinfo.Scene.SceneId;
                    string scanHandler = handler.OnEvent_SubscribeRequest(fromUserId, eventKey);
                    //if (!string.IsNullOrEmpty(eventKey) && !string.IsNullOrEmpty(scanHandler))
                    //    SendMessage.SendText(appId, fromUserId, scanHandler);
                }
                else if ("text".Equals(msgType))
                {
                    //文本
                    SendMessage.SendText(appId, fromUserId, handler.ProcessMessage(content, fromUserId));
                }
                else if ("image".Equals(msgType))
                {
                    //照片
                    //response.Message = new ParseMessageResponse.ImageMsg()
                    //{
                    //    MsgId = getXmlNode(biz_content, "MsgId"),
                    //    MediaId = getXmlNode(biz_content, "MediaId")
                    //};
                    SendMessage.SendText(appId,fromUserId,handler.GetWelcomeInfo());

                }
                else if ("click".Equals(eventType) && "authentication".Equals(actionParam))
                {
                    //添加商户账号绑定事件
                    var url = MessageHelper.GetH5Url("/index/manage-card");
                    reponseString = SendMessage.ReceivemsgResponse(appId, url, fromUserId);
                }
                else if ("click".Equals(eventType) && "delete".Equals(actionParam))
                {
                    //解除绑定商户账号事件
                    reponseString = "";
                }
                else if ("matchAuth".Equals(eventType, StringComparison.CurrentCultureIgnoreCase))
                {
                    //匹配用户发送模板
                    //response.MsgType = "event";

                }

                return new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new StringContent(reponseString)
                };
            }

            return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized");
        }

    }
}
